package com.itzjc.service.impl;

import com.itzjc.dao.ProjectMapper;
import com.itzjc.dao2.ProjectMapper2;
import com.itzjc.domain.entity.*;
import com.itzjc.domain.pojo.*;
import com.itzjc.service.ProjectService;
import com.itzjc.utils.JWTUtils;
import com.itzjc.utils.QiNiuUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @className: ProjectServiceImpl
 * @date: 2021-06-10 21:55
 **/
@Service
public class ProjectServiceImpl implements ProjectService {
    @Autowired(required = false)
    private ProjectMapper projectMapper;
    @Autowired(required = false)
    private ProjectMapper2 projectMapper2;

    @Override
    public List<ProjectInfo> getProjectByToken(Integer userId) {
        return projectMapper.findById(userId);
    }

    /**
     * 创建的时候可以默认图片，默认模型，这些后面都好说，这里记忆一下
     * 具体做法就是：在七牛云中存一个固定名称的文件（这个名称是UUID创建不出来的，所以可以保证唯一性）
     * 然后在创建的时候向图片和模型关联表中插入默认的名称
     *
     * @param requestProject
     * @return:
     **/

    @Override
    @Transactional(transactionManager = "test1TransactionManager")
    public String createProjectById(RequestProject requestProject) {
        //把项目表添加完成，需要返回添加项目成果的id，交给关系表构建
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setAddressDetails(requestProject.getAddress());
        projectInfo.setAuthorized(0);
        projectInfo.setCreateTime(new Date());
        projectInfo.setOpenStatus(0);
        projectInfo.setProjectName(requestProject.getProjectName());
        //此处就是添加的结构的类型信息
        projectInfo.setStype(Integer.valueOf(requestProject.getType()));
        //原始的项目是必须给一个id关联图片、obj、mtl文件的，因为这些文件都只写了更新的方法，但是没有写创建的方法
        //所以先把变量设定好，然后在对应方法中传入项目id（这个是唯一的，所以ok）和变量
        String img = "初始图片";
        String obj = "初始obj";
        String mtl = "初始mtl";

        //开始是没有创建的项目的id的，只有创建的方法完成以后，封装的projectInfo才是有id的,所以一个是请求的id，一个是查出来的id
        //原本的id都在token中，所以拿出来解析一下
        String token = requestProject.getToken();
        Claims claims = JWTUtils.checkJWT(token);
        if (null == claims) {
            return null;
        }
        Integer uid = (Integer) claims.get("id");


        //解析完毕以后，就算不登录也没有问题了,但是要判断一下有没有这个项目
        ProjectInfo projectInfo1 = projectMapper.beforeCreateProject(uid, projectInfo.getProjectName());
        //解析完毕，判断不是null以后才是添加关系表
        if (null == projectInfo1) {
            //插入到表格的语句不能写在前面，因为刚才发现，没有token的时候都创建成功了

            //而且，添加创建的操作一定要放到里面来，不然重复添加还是会在总表中添加的
            projectMapper.createProject(projectInfo);
            Integer pjId = projectInfo.getId();
            //添加用户-项目关系表
            projectMapper.createProjectById(uid, pjId);
            //添加项目-图片关系表
            projectMapper.createProjectImg(img, pjId);
            //添加项目-模型关系表
            projectMapper.createProjectModule(obj, mtl, pjId);

            //都成功以后就可以返回名称了
            String name = requestProject.getProjectName();
            return name;
        } else {
            //如果查出了重复项目就返回null，主要是返回300的状态码，前端就是根据这个状态码输出对应的语句的
            return null;
        }

    }

    @Override
    @Transactional(transactionManager = "test1TransactionManager")
    public void deleteProjectByToken(Integer userId, Integer projectId) {
        projectMapper.deleteProjectByToken(projectId);
        projectMapper.deleteProjectUzserByToken(userId, projectId);
    }

    @Override
    public List<ProjectInfo> getOpeningProjectByToken(Integer userId) {
        return projectMapper.findByIdAndOpeningStatus(userId);
    }

    @Override
    public List<ProjectInfo> getOpenedProjectByToken(Integer userId) {
        return projectMapper.findByIdAndOpenedStatus(userId);

    }

    @Override
    public List<ProjectInfo> getAuthorizingProjectByToken(Integer userId) {
        return projectMapper.findByIdAndauthorizing(userId);
    }

    @Override
    public List<ProjectInfo> getAuthorizedProjectByToken(Integer userId) {
        return projectMapper.findByIdAndauthorized(userId);
    }

    @Override
    public CurrentProjectInfo getProjectInfoByTokenAndId(Integer userId, Integer projectId) {
        CurrentProjectInfo currentProjectInfo = new CurrentProjectInfo();
        Integer count = projectMapper.exitProject(userId, projectId);
        if (0 == count) {
            return null;
        }
        //查询基础信息
        ProjectInfo projectInfo = projectMapper.getProjectById(projectId);
        currentProjectInfo.setProjectName(projectInfo.getProjectName());
        currentProjectInfo.setAddress(projectInfo.getAddressDetails());
        currentProjectInfo.setCreateTime(projectInfo.getCreateTime());
        currentProjectInfo.setId(projectId);

        //查询结构类型
        String type = projectMapper.getType(projectInfo.getStype());
        currentProjectInfo.setType(type);
        currentProjectInfo.setOwnerId(userId);
        //查询图片
        String imgName = projectMapper.getProjectImg(projectId);
        currentProjectInfo.setImg(QiNiuUtils.DOMAIN + imgName);
        //查询模型obj信息
        String objName = projectMapper.getProjectObj(projectId);
        currentProjectInfo.setObj(QiNiuUtils.DOMAIN + objName);
        //查询模型mtl信息
        String mtlName = projectMapper.getProjectMtl(projectId);
        currentProjectInfo.setMtl(QiNiuUtils.DOMAIN + mtlName);
        //查询风信息
        Double windValue01 = projectMapper.getMaxWindValue(projectId);
        if (null != windValue01) {
            currentProjectInfo.setWindValue01(windValue01);

        } else {
            currentProjectInfo.setWindValue01(0.0);
        }


        //查询温度信息
        Double temperatureValue01 = projectMapper.getMaxTemperatureValue(projectId);
        if (null != temperatureValue01) {
            currentProjectInfo.setTemperatureValue01(temperatureValue01);

        } else {
            currentProjectInfo.setTemperatureValue01(0.0);
        }

        //查询挠度信息
        Double deflectionValue01 = projectMapper.getMaxDeflectionValue(projectId);
        if (null != deflectionValue01) {
            currentProjectInfo.setDeflectionValue01(deflectionValue01);

        } else {
            currentProjectInfo.setDeflectionValue01(0.0);
        }

        //查询应力信息
        Double stressValue01 = projectMapper.getMaxStressValue(projectId);
        if (null != stressValue01) {
            currentProjectInfo.setStressValue01(stressValue01);

        } else {
            currentProjectInfo.setStressValue01(0.0);
        }

        //查询损伤和安全等级
        LifeEstimationInfo lifeEstimationInfo = projectMapper.getLifeEstimationInfo(projectId);
        if (null != lifeEstimationInfo) {

        } else {
            LifeEstimationInfo lifeEstimationInfo1 = new LifeEstimationInfo();

            lifeEstimationInfo1.setDamageTimes(0);
            lifeEstimationInfo1.setStatusLevel("无数据");
            lifeEstimationInfo=lifeEstimationInfo1;
        }
        currentProjectInfo.setLifeEstimationInfo(lifeEstimationInfo);

        //查询位移信息
        Double dispalcementValue01 = projectMapper.getMaxDispalcementValue(projectId);
        if (null != dispalcementValue01) {
            currentProjectInfo.setDispalcementValue01(dispalcementValue01);

        } else {
            currentProjectInfo.setDispalcementValue01(0.0);
        }
        return currentProjectInfo;
    }

    @Override
    public String updateProjectImg(RequestImage requestImage) {
        Integer projectId = Integer.valueOf(requestImage.getProjectId());
        Integer uid = Integer.valueOf(requestImage.getUid());
        Integer count = projectMapper.exitProject(uid, projectId);
        if (0 == count) {
            return null;
        }

        String img = requestImage.getImgName();
        projectMapper.updateProjectImg(img, projectId);
        return "更新成功";
    }

    @Override
    public void updateWholeProject(RequestUpdateAllProject requestUpdateAllProject) {
        //没必要查出原来的，修改了哪些就更新哪些就行了，没有修改的字段就不动就行了
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setAddressDetails(requestUpdateAllProject.getAddress());
        projectInfo.setProjectName(requestUpdateAllProject.getProjectName());
        projectInfo.setStype(Integer.valueOf(requestUpdateAllProject.getStructuralType()));
        projectInfo.setCity(requestUpdateAllProject.getCtiy());
        projectInfo.setProvince(requestUpdateAllProject.getProvince());
        projectInfo.setId(Integer.valueOf(requestUpdateAllProject.getProjectId()));
        //想利用外部的id查询的思路失败了，改成把id内置的查询方式
        projectMapper.updateWholeProject(projectInfo);


    }

    @Override
    public String updateProjectModule(RequestModule requestModule) {
        Integer projectId = Integer.valueOf(requestModule.getProjectId());
        Integer uid = Integer.valueOf(requestModule.getUid());
        Integer count = projectMapper.exitProject(uid, projectId);
        if (0 == count) {
            return null;
        }
        String obj = requestModule.getObjName();
        String mtl = requestModule.getMtlName();

        projectMapper.updateProjectModule(obj, mtl, projectId);
        return "更新成功";
    }

    @Override
    public List<BigInteger> findByIdForSecondSource(int id) {
        return projectMapper2.findByIdForSecondSource(id);
    }

    @Override
    public void generateForgetCode(Integer userId, String info) {
        //判断一下用户权限
        //如果这个ID的status是2就执行，如果不是就说明系统漏洞，进行任何操作
        Integer status=projectMapper.findStatusById(userId);
        if (status==2){     //项目表中删除
            projectMapper.generateForgetCode(info);}


    }

    @Override
    public CurrentProjectInfo guestGetProjectInfo(Integer projectId) {
        CurrentProjectInfo currentProjectInfo = new CurrentProjectInfo();

        //查询基础信息
        ProjectInfo projectInfo = projectMapper.getProjectById(projectId);
        currentProjectInfo.setProjectName(projectInfo.getProjectName());
        currentProjectInfo.setAddress(projectInfo.getAddressDetails());
        currentProjectInfo.setCreateTime(projectInfo.getCreateTime());
        currentProjectInfo.setId(projectId);

        //查询结构类型
        String type = projectMapper.getType(projectInfo.getStype());
        currentProjectInfo.setType(type);

        //查询图片
        String imgName = projectMapper.getProjectImg(projectId);
        currentProjectInfo.setImg(QiNiuUtils.DOMAIN + imgName);
        //查询模型obj信息
        String objName = projectMapper.getProjectObj(projectId);
        currentProjectInfo.setObj(QiNiuUtils.DOMAIN + objName);
        //查询模型mtl信息
        String mtlName = projectMapper.getProjectMtl(projectId);
        currentProjectInfo.setMtl(QiNiuUtils.DOMAIN + mtlName);
        //查询风信息
        Double windValue01 = projectMapper.getMaxWindValue(projectId);
        if (null != windValue01) {
            currentProjectInfo.setWindValue01(windValue01);

        } else {
            currentProjectInfo.setWindValue01(0.0);
        }


        //查询温度信息
        Double temperatureValue01 = projectMapper.getMaxTemperatureValue(projectId);
        if (null != temperatureValue01) {
            currentProjectInfo.setTemperatureValue01(temperatureValue01);

        } else {
            currentProjectInfo.setTemperatureValue01(0.0);
        }

        //查询挠度信息
        Double deflectionValue01 = projectMapper.getMaxDeflectionValue(projectId);
        if (null != deflectionValue01) {
            currentProjectInfo.setDeflectionValue01(deflectionValue01);

        } else {
            currentProjectInfo.setDeflectionValue01(0.0);
        }

        //查询应力信息
        Double stressValue01 = projectMapper.getMaxStressValue(projectId);
        if (null != stressValue01) {
            currentProjectInfo.setStressValue01(stressValue01);

        } else {
            currentProjectInfo.setStressValue01(0.0);
        }

        //查询损伤和安全等级
        LifeEstimationInfo lifeEstimationInfo = projectMapper.getLifeEstimationInfo(projectId);
        if (null != lifeEstimationInfo) {

        } else {
            LifeEstimationInfo lifeEstimationInfo1 = new LifeEstimationInfo();

            lifeEstimationInfo1.setDamageTimes(0);
            lifeEstimationInfo1.setStatusLevel("无数据");
            lifeEstimationInfo=lifeEstimationInfo1;
        }
        currentProjectInfo.setLifeEstimationInfo(lifeEstimationInfo);

        //查询位移信息
        Double dispalcementValue01 = projectMapper.getMaxDispalcementValue(projectId);
        if (null != dispalcementValue01) {
            currentProjectInfo.setDispalcementValue01(dispalcementValue01);

        } else {
            currentProjectInfo.setDispalcementValue01(0.0);
        }
        return currentProjectInfo;
    }
}
